package com.dk.smsexpress.server.utils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


/**
 * To parse XML to list of object. 
 * 
 * 
 * @author tnguyen271
 *
 */
public class XMLUtils {
	
	/**
	 * Parse XML to map object
	 * @param filename the filename to parse
	 * @param root the root of xml tag
	 * @param tags all of the tags to parse
	 * @return 
	 * @throws ParserConfigurationException 
	 * @throws IOException 
	 * @throws SAXException 
	 */
	public static List<Map<String,String>> parseXML(String filename, String root, String... tags) throws ParserConfigurationException, SAXException, IOException{
				 
		File file = new File(filename);
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(file);
		doc.getDocumentElement().normalize(); 
		NodeList nodeLst = doc.getElementsByTagName(root); 
		
		List<Map<String,String>> results = new ArrayList<Map<String,String>>();
		for (int s = 0; s < nodeLst.getLength(); s++) {
			Node fstNode = nodeLst.item(s);
			if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
				Element fstElmnt = (Element) fstNode;
				Map<String,String> result = new HashMap<String, String>();
				for (String tag: tags){
					NodeList fstNmElmntLst = fstElmnt.getElementsByTagName(tag);
					Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
					NodeList fstNm = fstNmElmnt.getChildNodes();
					result.put(tag, ((Node) fstNm.item(0)).getNodeValue());
				}
				results.add(result);
			}
		}
		return results;
	} 
}
